// 测试视频下载助手 - 页面注入脚本

(function() {
  'use strict'
  
  console.log('测试视频下载助手页面脚本已注入')
  
  // 监听页面中的视频相关事件
  class VideoMonitor {
    constructor() {
      this.init()
    }
    
    init() {
      // 监听视频加载
      this.monitorVideoLoad()
      
      // 监听页面变化
      this.monitorPageChange()
      
      // 拦截网络请求
      this.interceptRequests()
    }
    
    // 监听视频加载
    monitorVideoLoad() {
      const videos = document.querySelectorAll('video')
      videos.forEach(video => {
        video.addEventListener('loadedmetadata', () => {
          console.log('视频已加载:', video.src)
          this.notifyVideoLoaded(video)
        })
      })
      
      // 使用MutationObserver监听新添加的视频元素
      const observer = new MutationObserver(mutations => {
        mutations.forEach(mutation => {
          mutation.addedNodes.forEach(node => {
            if (node.nodeType === 1) { // Element node
              const videos = node.querySelectorAll ? node.querySelectorAll('video') : []
              videos.forEach(video => {
                video.addEventListener('loadedmetadata', () => {
                  console.log('新视频已加载:', video.src)
                  this.notifyVideoLoaded(video)
                })
              })
            }
          })
        })
      })
      
      observer.observe(document.body, {
        childList: true,
        subtree: true
      })
    }
    
    // 监听页面变化
    monitorPageChange() {
      let currentUrl = window.location.href
      
      // 监听URL变化（SPA应用）
      const checkUrlChange = () => {
        if (window.location.href !== currentUrl) {
          currentUrl = window.location.href
          console.log('页面URL已变化:', currentUrl)
          this.notifyPageChange()
        }
      }
      
      // 监听pushState和replaceState
      const originalPushState = history.pushState
      const originalReplaceState = history.replaceState
      
      history.pushState = function() {
        originalPushState.apply(history, arguments)
        setTimeout(checkUrlChange, 100)
      }
      
      history.replaceState = function() {
        originalReplaceState.apply(history, arguments)
        setTimeout(checkUrlChange, 100)
      }
      
      // 监听popstate事件
      window.addEventListener('popstate', checkUrlChange)
      
      // 定期检查URL变化
      setInterval(checkUrlChange, 1000)
    }
    
    // 拦截网络请求
    interceptRequests() {
      // 拦截fetch请求
      const originalFetch = window.fetch
      window.fetch = async function(...args) {
        const response = await originalFetch.apply(this, args)
        
        // 检查是否为视频相关请求
        const url = args[0]
        if (typeof url === 'string' && this.isVideoUrl(url)) {
          console.log('拦截到视频请求:', url)
          this.notifyVideoRequest(url, response)
        }
        
        return response
      }.bind(this)
      
      // 拦截XMLHttpRequest
      const originalOpen = XMLHttpRequest.prototype.open
      XMLHttpRequest.prototype.open = function(method, url) {
        if (this.isVideoUrl(url)) {
          console.log('拦截到XHR视频请求:', url)
          this.addEventListener('load', () => {
            this.notifyVideoRequest(url, this)
          }.bind(this))
        }
        
        return originalOpen.apply(this, arguments)
      }.bind(this)
    }
    
    // 判断是否为视频URL
    isVideoUrl(url) {
      if (!url) return false
      
      const videoExtensions = ['.mp4', '.avi', '.mkv', '.mov', '.wmv', '.flv', '.webm', '.m3u8']
      const videoKeywords = ['video', 'stream', 'play', 'media']
      
      return videoExtensions.some(ext => url.includes(ext)) ||
             videoKeywords.some(keyword => url.toLowerCase().includes(keyword))
    }
    
    // 通知视频已加载
    notifyVideoLoaded(video) {
      window.postMessage({
        type: 'VIDEO_LOADED',
        data: {
          src: video.src,
          duration: video.duration,
          videoWidth: video.videoWidth,
          videoHeight: video.videoHeight
        }
      }, '*')
    }
    
    // 通知页面变化
    notifyPageChange() {
      window.postMessage({
        type: 'PAGE_CHANGED',
        data: {
          url: window.location.href,
          title: document.title
        }
      }, '*')
    }
    
    // 通知视频请求
    notifyVideoRequest(url, response) {
      window.postMessage({
        type: 'VIDEO_REQUEST',
        data: {
          url: url,
          status: response.status || 200,
          headers: response.headers || {}
        }
      }, '*')
    }
  }
  
  // 初始化视频监控
  new VideoMonitor()
  
  // 添加全局方法供content script调用
  window.testDownloaderHelper = {
    // 获取当前页面的视频信息
    getVideoInfo() {
      const videos = document.querySelectorAll('video')
      const videoInfo = []
      
      videos.forEach(video => {
        if (video.src) {
          videoInfo.push({
            src: video.src,
            duration: video.duration,
            width: video.videoWidth,
            height: video.videoHeight,
            currentTime: video.currentTime
          })
        }
      })
      
      return videoInfo
    },
    
    // 获取页面中的所有视频链接
    getVideoLinks() {
      const links = document.querySelectorAll('a[href*="video"], a[href*="play"], a[href*="watch"]')
      const videoLinks = []
      
      links.forEach(link => {
        videoLinks.push({
          href: link.href,
          text: link.textContent.trim(),
          title: link.title || link.getAttribute('data-title') || ''
        })
      })
      
      return videoLinks
    },
    
    // 获取课程信息
    getCourseInfo() {
      return {
        title: document.querySelector('h1, .course-title, .title')?.textContent?.trim() || '',
        instructor: document.querySelector('.instructor, .teacher')?.textContent?.trim() || '',
        description: document.querySelector('.description, .intro')?.textContent?.trim() || ''
      }
    }
  }
  
})()